﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.IO;
using Newtonsoft.Json;

namespace OnTheWay.Tool
{
    public class LightCache : XmlHelper
    {
        public class CacheEntity
        {
            public CacheEntity(string key, object value)
            {
                // TODO: Complete member initialization
                this.Key = key;
                this.Type = value.GetType().FullName;
                this.Value = JsonConvert.SerializeObject(value);
            }
            public string Key { get; set; }
            public string Type { get; set; }
            public string Value { get; set; }
        }

        public LightCache()
            : base("LightCache")
        {

        }

        public LightCache(string path)
            : base(path)
        {

        }

        public void Put(string key,object value)
        {
            XmlElement element = this.CreateElement(key);
            CacheEntity entity = new CacheEntity(key, value);
            BindingElement(ref element, entity);
            XmlNodeList keys = this.mRootNode.GetElementsByTagName(key);
            for (int i = keys.Count-1;i >= 0;i--)
            {
                this.mRootNode.RemoveChild(keys[i]);
            }
            this.mRootNode.AppendChild(element);
            this.Save();
        }

        public T Get<T>(string key)
        {
            return Get<T>(key,default(T));
        }

        public T Get<T>(string key,T _default)
        {
            XmlNodeList keys = this.mRootNode.GetElementsByTagName(key);
            if (keys != null && keys.Count == 1)
            {
                XmlNode node = keys[0];
                if (typeof(T).FullName == node.Attributes["Type"].Value.ToString())
                {
                    return JsonConvert.DeserializeObject<T>(node.Attributes["Value"].Value.ToString());
                }
            }
            return _default;
        }
    }
}
